import { subscribe } from 'valtio'
import { proxyWithHistory } from 'valtio/utils'

import type { JSONSchema } from './Schema'
import { createId } from '@/utils'

export const jsonSchema = proxyWithHistory<JSONSchema>((JSON.parse(localStorage.getItem('jsonSchema') as any)) || {
  componentsTree: [{
    componentid: createId(),
    $componentName: 'Page',
    fileName: 'Page1',
    hasSlot: true,
  }],
  componentsMap: [],
})

export function deleteJsonSchemaItem(id: string) {
  function delItem(arr: any) {
    for (const key in arr) {
      if (arr[key] && arr[key].componentid && arr[key].componentid === id) {
        if (Array.isArray(arr))
          arr.splice(Number(key), 1)
        else
          delete arr[key]

        return true
      }
      else if (typeof arr[key] === 'object') {
        delItem(arr[key])
      }
    }
    return false
  }
  return delItem(jsonSchema.value.componentsTree)
}

subscribe(jsonSchema, () => {
  localStorage.setItem('jsonSchema', JSON.stringify(jsonSchema.value))
})
